package it.ap.sa.core.dao.util.serializer;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.PrecisionModel;
import com.vividsolutions.jts.io.ParseException;
import com.vividsolutions.jts.io.WKTReader;

/**
 *
 */
public class WKT3rdDeserializer extends JsonDeserializer<Geometry> {

	@Override
	public Geometry deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
		ObjectCodec oc = jp.getCodec();
		JsonNode root = oc.readTree(jp);
		return parseGeometry(root);
	}

	/**
	 * Es json : "geometry":{"wkt":"POINT(16.27582497094736 41.16401442647753)"}
	 * 
	 * @param root
	 * @return
	 */
	private Geometry parseGeometry(JsonNode root) {
		String wkt = root.get("wkt").asText();
		/**
		 * Costruisco una GeometryFactory che genera geometrie che hanno un
		 * dato PrecisionModel e ID spaziale di riferimento.
		 * **/
		GeometryFactory factoryLine = new GeometryFactory(new PrecisionModel(), 4326);

		/**
		 * "WKTReader": Legge una rappresentazione WKT di una geometria da
		 * una stringa.
		 **/
		WKTReader wKTReader = new com.vividsolutions.jts.io.WKTReader(factoryLine);
		
		Geometry ret= null;
		try {
			/** creo la geometry **/
			ret = wKTReader.read(wkt);
			
		} catch (ParseException e) {
			e.printStackTrace();
		}
	    return ret;
	}
}
